<?php
require_once dirname(__FILE__) . '/simple_html_dom.php';
require_once dirname(__FILE__) . '/../environment.php';

class Editor_Controller
{
	const FILENAME_BASE = 'file_base.inf';
	const UID_PREFIX = 'u';
	protected $_stackUid = 1000;

	public function createHtml($jquery='',$form='')
	{
		$contents = 'empty';
		if (isset($_REQUEST['editor1'])){
			$contents = $_REQUEST['editor1'];
			$contents = $this->setMacro($contents);
			$contents = $this->replaceDropboxImageUrl($contents);
		}
		$title = self::getH1FromHtml($contents);
		if (!empty($_REQUEST['pagetitle'])) {
			$title = $_REQUEST['pagetitle'];
		}
		if ($title == '') {
			$title = 'notitle';
		}
		$keywords = '';
		if (!empty($_REQUEST['keywords'])) {
			$keywords = str_replace(' ', '', $_REQUEST['keywords']);
		}
		$新規ページリンク = env::APPLICATION_BASE_PATH . 'editor/';
		global $htmlFileName;
		$自身編集リンク = env::APPLICATION_BASE_PATH . 'editor/?load=' . $htmlFileName;
		$トップページリンク = env::APPLICATION_BASE_PATH . 'contents/frameset.php';
		$html = file_get_contents(dirname(__FILE__).'/modify.tpl');
		$html = str_replace('{?TITLE?}', $title, $html);
		$html = str_replace('{?KEYWORDS?}', $keywords, $html);
		$html = str_replace('{?JQUERY?}', $jquery, $html);
		$html = str_replace('{?CONTENTS?}', $contents, $html);
		$html = str_replace('{?BODY_CONTROLLER?}', $form, $html);
		$html = str_replace('{?CREATE_NEW?}', $新規ページリンク, $html);
		$html = str_replace('{?EDITOR_HREF?}', $自身編集リンク, $html);
		$html = str_replace('{?TOP_LINK?}', $トップページリンク, $html);
		return $html;
	}

	protected function setMacro($contents)
	{
		$lines = explode("\r\n", $contents);
		foreach ($lines as &$line) {
			$line = $this->disideExpandStartLocal($line);
			$line = $this->disideExpandEndLocal($line);
		}
		$result = implode("\r\n", $lines);
		return $result;
	}

	/**
	 * ドロップボックスのヘッダ付き画像URLをヘッダ無し直林に書き換える
	 * @param unknown $contents
	 * @return unknown
	 */
	protected function replaceDropboxImageUrl($contents)
	{
		$contents = str_replace('src="https://www.dropbox.com', 'src="https://dl-web.dropbox.com', $contents);
		return $contents;
	}

	static public function fetchMarty($aryKeyValues, $source)
	{
		foreach($aryKeyValues as $key=>$value) {
			$source = str_replace($key, $value, $source);
		}
		return $source;
	}

	static public function createFileName()
	{
		$baseFileName = dirname(__FILE__) .'/'.self::FILENAME_BASE;
		$fileNum = 0;
		if (file_exists($baseFileName)) {
			$fileNum = file_get_contents($baseFileName);
		}
		$fileNum ++;
		$htmlFileName = sprintf('%04x.html', $fileNum);
		file_put_contents($baseFileName, $fileNum);
		return $htmlFileName;
	}

	static public function setAllowEdit()
	{
		if (!isset($_SESSION)) {
			session_start();
		}
		$_SESSION['edit'] = 'OK';
	}

	static public function isAllowEdit()
	{
		if (!isset($_SESSION)) {
			session_start();
		}
		$result = FALSE;
		if (isset($_SESSION['edit'])) {
			if ($_SESSION['edit'] == 'OK') {
				$result = TRUE;
			}
		}
		return $result;
	}

	static function getFromBodyToBody2($htmlFile)
	{
		$html = file_get_html($htmlFile);
		$result = $html->find('body');
		$aryResult = array();
		foreach($result as $list) {
			$aryResult[] = $list->innertext;
		}
		return $aryResult[0];
	}

	static function getFromBodyToBody($htmlFile)
	{
		$html = file($htmlFile, FILE_IGNORE_NEW_LINES);
		$lineCount = count($html);
		$i = 0;
		while ($i < $lineCount) {
			if (trim($html[$i]) == '<body>') {
				break;
			}
			$i ++;
		}
		$aryResult = array();
		$i ++;
		while ($i < $lineCount) {
			if (trim($html[$i] == '</body>')) {
				break;
			}
			$aryResult[] = $html[$i];
			$i ++;
		}

		foreach ($aryResult as &$line) {
			$line = self::disideExpandStartHtml($line);
			$line = self::isExpandEndHtml($line);
		}

		$sResult = implode("\n", $aryResult);
		$sResult = self::SpecialCharactorToMultibyte($sResult);
		return $sResult;
	}

	static function SpecialCharactorToMultibyte($text)
	{
		$specialCharactors = array(
			'&gt;' => '＞',
			'&lt;' => '＜'
		);
		foreach ($specialCharactors as $sc=>$mb) {
			$text = str_replace($sc, $mb, $text);
		}
		return $text;
	}

	static function getH1FromHtml($sourse) {
		$html = str_get_html ( $sourse );
		$result = $html->find ( 'h1' );
		$aryResult = array ();
		foreach ( $result as $list ) {
			$aryResult [] = $list->innertext;
		}
		$html->clear ();
		$result = '';
		if (count ( $result ) > 0) {
			$result = $aryResult [0];
		}
		return $result;
	}

	static function getTitleFromHtmlFile($htmlFile)
	{
		$html = file_get_html($htmlFile);
		$result = $html->find('title');
		$aryResult = array();
		foreach($result as $list) {
			$aryResult[] = $list->innertext;
		}
		$html->clear();
		return $aryResult[0];
	}

	static function getKeywordsFromHtmlFile($htmlFile)
	{
		$keywords = '';
		$html = file_get_html($htmlFile);
		$meta = $html->find('meta[name=keywords]',0,true);
		if ($meta instanceof simple_html_dom_node) {
			$keywords = $meta->attr['content'];
		}
		return $keywords;
	}

	/**
	 * 文字列がlocal htmlの展開開始行であれば展開アンカー文字列を返す
	 * @param unknown $line
	 */
	const KEY_EXPAND_START_LOCAL = '<span style="color:#D3D3D3">｛展開：';
	static public function createUnch($line)
	{
		$anch = FALSE;
		/*** 展開開始行判定 */
		if (strpos($line, self::KEY_EXPAND_START_LOCAL) === FALSE) {
			return FALSE;
		}

		/*** ｛｝内文字列抽出 */
		$pos = strpos($line, self::KEY_EXPAND_START_LOCAL);
		$startPos = $pos + strlen(self::KEY_EXPAND_START_LOCAL);
		$buff = substr($line,$startPos);
		$endPos = strpos($buff,'｝');
		/*** 閉じていない場合は展開開始行ではないと判定 */
		if ($endPos === FALSE) {
			return FALSE;
		}
		$buff = substr($buff,0,$endPos);

		/*** アンカー文字抽出 */
		$anch = '＜展開部＞';
		if ($buff != '') {
			$anch = $buff;
		}

		return $anch;
	}


	/**
	 * UID採番
	 */
	protected function _createUid()
	{
		$this->_stackUid ++;
		return self::UID_PREFIX . $this->_stackUid;
	}

	/**
	 * 指定文字列が展開ブロック開始部であるか判定し
	 * 展開ブロック開始HTMLコードに置き換える
	 * @param unknown $line
	 */
	public function disideExpandStartLocal($line)
	{
		$anch = self::createUnch($line);
		if ($anch === FALSE) {
			return $line;
		}
		$uid = $this->_createUid();
		$line = self::createExpandStartHtml($anch, $uid);
		return $line;
	}

	/**
	 * 展開ブロック開始ＨＴＭＬコードを作成する
	 * @param unknown $anch
	 * @param unknown $uid
	 */
	const VALUE_EXPAND_START_HTML = "<div class=\"WKRD-展開\" style=\"text-align: right;\" id=\"openxxx\" value=\"アンカー文言\" ><div onClick=\"$('#xxx').show('slow');$('#openxxx').hide('slow');$('#closexxx').show('slow');\">アンカー文言</div></div><div id=\"xxx\" style=\"display:none\" class=\"WKRD-展開ボディ\"><div id=\"closexxx\" style=\"display:none\" onClick=\"$('#xxx').hide('slow');$('#openxxx').show('slow')\">アンカー文言（閉じる）</div>";
	static public function createExpandStartHtml($anch,$uid)
	{
		$result = str_replace('アンカー文言', $anch, self::VALUE_EXPAND_START_HTML);
		$result = str_replace('xxx', $uid, $result);
		return $result;
	}

	/**
	 * 指定文字列が展開ブロック終了部であるか判定し
	 * 展開ブロック終了HTMLコードに置き換える
	 * @param unknown $line
	 */
	const KEY_EXPAND_END_LOCAL = '<span style="color:#D3D3D3">｛展開｝';
	const VALUE_EXPAND_END_HTML = '</div><!-- WKRD展開  -->';
	public function disideExpandEndLocal($line)
	{
		/*** 展開開始行判定 */
		if (strpos($line, self::KEY_EXPAND_END_LOCAL) === FALSE) {
			return $line;
		}

		$line = self::VALUE_EXPAND_END_HTML;
		return $line;
	}

	/**
	 * 文字列が htmlの展開開始行であればlocal htmlに変換する
	 * @param unknown $line
	 */
	const KEY_EXPAND_START_HTML = '<div class="WKRD-展開"';
	const KEY_EXPAND_START = '<div style="text-align: right;"><span style="color:#D3D3D3">｛展開：アンカー文言｝</span></div>';
	static public function disideExpandStartHtml($line)
	{
		if ( mb_strpos($line,self::KEY_EXPAND_START_HTML) === FALSE) {
			return $line;
		}
		$dom = str_get_html($line);
		$anch = $dom->find('div', 0)->value;
		$result = str_replace('アンカー文言', $anch, self::KEY_EXPAND_START);
		return $result;
	}

	/**
	 * 文字列がhtmlの展開終了行であればtrueを返す
	 * @param unknown $line
	 * @return boolean
	 */
	const KEY_EXPAND_END = '<div style="text-align: right;"><span style="color:#D3D3D3">｛展開｝</div>';
	static public function isExpandEndHtml($line)
	{
		$result = $line;
		if (mb_strpos($line, self::VALUE_EXPAND_END_HTML) !== FALSE) {
			$result = self::KEY_EXPAND_END;
		}
		return $result;
	}

}

